#include <stdio.h>
#include <string.h>

#include "cJSON.h"
#include "curl/curl.h"

#include "cicd_config.h"
#include "msg_manager.h"
#include "message_queue.h"
#include "cicd_common.h"

static size_t wirte_callback(void *contents, size_t size, size_t nmemb, char *output) {
    size_t total_size = size * nmemb;
    memcpy(output, contents, total_size);
    return total_size;
}

void msg_get_all_repo_status(const char *access_token, const char *owner, const char *repo, repo_handler *handler) {
    CURL *curl = NULL;
    char url[512] = { 0 };
    char out[10240] = { 0 };
    struct curl_slist *headers = NULL;
    CURLcode curl_ret = 0;
    long http_code;

    cJSON *root = NULL;
    int i;

    printf_debug("into msg_get_all_repo_status\n");

    snprintf(url, sizeof(url), "%s/%s/%s/branches?access_token=%s", global_https_header, owner, repo, access_token);
    printf_debug("request url: %s\n", url);
    headers = curl_slist_append(headers, global_request_header);
    if(NULL == headers) {
        printf_error("In function %s, headers is NULL\n", __FUNCTION__);
        goto exit;
    }

    curl = curl_easy_init();
    printf_debug("curl init ok\n");
    if(NULL == curl) {
        printf_error("In function %s, curl init failed\n", __FUNCTION__);
        goto exit;
    }
    curl_easy_setopt(curl, CURLOPT_URL, url);
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, wirte_callback);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, out);

    curl_ret = curl_easy_perform(curl);
    printf_debug("curl ret is %d\n", curl_ret);
    if(CURLE_OK != curl_ret) {
        printf_warning("In function %s, curl return error, url is %s\n", __FUNCTION__, url);
        goto exit;
    }
    curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code);
    printf_debug("curl get info ok\n");
    if(200 != http_code) {
        printf_warning("In function %s, http code is %ld. Think this is a warning.\n", __FUNCTION__, http_code);
        goto exit;
    }

    printf_success("Successfully obtained status information\n");

    root = cJSON_Parse(out);
    printf_debug("json parse ok\n");
    if(NULL == root) {
        printf_error("In function %s. Getting status successfully but JSON parsing error. consider this a mistake.", __FUNCTION__);
        goto exit;
    }

    repo_update_by_json(handler, repo, root);
    printf_debug("repo_update_by_json ok\n");
exit:
    curl_easy_cleanup(curl);
    curl_slist_free_all(headers);
    cJSON_Delete(root);
    printf_debug("out msg_get_all_repo_status\n");
    return;
}
